package com.zhongxi.guoyuan.view.beautifulStore;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.BannerAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.gift.ShareBeautifulResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectDetailData;
import com.zhongxi.guoyuan.entity.projectItem.ProjectDetailResult;
import com.zhongxi.guoyuan.fragment.beautifulStore.BeautifulStoreCommentFragment;
import com.zhongxi.guoyuan.fragment.beautifulStore.BeautifulStoreDetailFragment;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProjectDetailActivity extends BaseActivity implements View.OnClickListener, MyScrollView.OnScrollListener {

    private List<String> data = new ArrayList<String>();
    private BannerAdapter mBannerAdapter;
    private Button btComment;
    private Button btDetail;
    private ViewFlow myViewFlow;
    private BeautifulStoreDetailFragment detailFragment;
    private BeautifulStoreCommentFragment commentFragment;
    private Fragment[] fragments;
    private int index = 0;
    private int currentIndex = 0;
    private Button[] tabs;
    private LinearLayout linearLayout;
    private LinearLayout linearScrollBody;
    private LinearLayout linearBegin;
    private LinearLayout linearStop;
    private int scrollHeight;
    private MyScrollView scrollView;
    private TextView tvOrder;
    private String id;
    private TextView tvName;
    private TextView tvMeibi;
    private TextView tvOrign;
    private TextView tvView;
    private TextView tvTime;
    private TextView tvNum;
    private TextView tvCash;
    private TextView tvReward;
    private ProjectDetailData basicData;
    private UMShareAPI mShareAPI;
    private SHARE_MEDIA platform;
    private View popupWindow_view;
    private PopupWindow popupWindow;
    private Map<String, String> map = new HashMap<String, String>();
    private String type;
    private ProjectDetailResult result;
    private Button btShare;
    private Button btCollection;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
            scrollHeight = linearLayout.getBottom();//获取searchLayout的顶部位置
        }
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_project_detail);

        mShareAPI = UMShareAPI.get(this);

        id = getIntent().getStringExtra("id");
        initTitle();
        tvTitle.setText("项目详情");
        myViewFlow = (ViewFlow) findViewById(R.id.viewflowproject);

        btDetail = (Button) findViewById(R.id.btDetail);
        btComment = (Button) findViewById(R.id.btComment);
        btDetail.setSelected(true);

        tvName = (TextView) findViewById(R.id.tvName);
        tvMeibi = (TextView) findViewById(R.id.tvMeibi);
        tvOrign = (TextView) findViewById(R.id.tvOrign);
        tvView = (TextView) findViewById(R.id.tvView);
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvNum = (TextView) findViewById(R.id.tvNum);
        tvCash = (TextView) findViewById(R.id.tvCash);
        tvReward = (TextView) findViewById(R.id.tvReward);
        btShare = (Button) findViewById(R.id.btShare);
        btCollection = (Button) findViewById(R.id.btCollection);

        RelativeLayout frame = (RelativeLayout) findViewById(R.id.frame);
        ImageUtils.setHeight(this, Constants.detailRate, frame);

        //上拉悬停
        scrollStop();

        InitViewPager();

        tvOrder = (TextView) findViewById(R.id.tvOrder);
    }

    /**
     *
     */
    @Override
    protected void initData() {
        super.initData();
        type = "detail";
        getServer(Url.SERVICE_DETAILS, null,"&sid="+id, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("detail".equals(type)) {
                result = gson.fromJson(response, ProjectDetailResult.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                data = result.getBasic().getImages();
                if (data.size() > 0) {
                    tvNum.setText(data.size()+"");
                    myViewFlow.setSideBuffer(data.size()); // 实际图片数量
                }
                if (mBannerAdapter == null) {
                    mBannerAdapter = new BannerAdapter(context, data);
                    myViewFlow.setAdapter(mBannerAdapter);
                } else {
                    mBannerAdapter.replaceAll(data);
                }
                //初始化基本数据
                initProjectData(result);
            }else if("collection".equals(type)){
                BaseResponse res = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(res.getSafeobj());
                showShortToast("收藏成功！");
            }else if("shareget".equals(type)){
                ShareBeautifulResult result = gson.fromJson(response, ShareBeautifulResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                showPopupWindow(result.getNum());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void showPopupWindow(String num) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_share, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(layout);

        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        TextView tvTips = (TextView) layout.findViewById(R.id.tvTips);
        TextView tvQuit = (TextView) layout.findViewById(R.id.tvQuit);

        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvTips.setText("成功分享获得"+num+"个美币");
        tvQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse res = gson.fromJson(response, BaseResponse.class);
            if (null != res.getSafeobj() && !"".equals(res.getSafeobj()))
                MyApplication.getInstance().setSpValue(res.getSafeobj());
            if(res.getCode() == 1000){
                showShortToast("该项目已下架！");
                finish();
            }
            if ("collection".equals(type)) {
                if (6206 == res.getCode()) {
                    showShortToast("该项目已经收藏");
                } else if (1001 == res.getCode()) {
                    showShortToast("用户未登录，请先登录");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 初始化项目详情数据
     * @param result
     */
    private void initProjectData(ProjectDetailResult result) {
        try{
            if(null!=result.getBasic()&&!"".equals(result.getBasic())){
                basicData = result.getBasic();
                if(null!=basicData.getName()&&!"".equals(basicData.getName())){
                    tvName.setText(basicData.getName());
                }else{
                    tvName.setText("");
                }
//                if(null!=basicData.getInnerprice()&&!"".equals(basicData.getInnerprice())){
//                    tvMeibi.setText(basicData.getInnerprice());
//                }else{
//                    tvMeibi.setText("");
//                }
                if(null!=basicData.getPrice()&&!"".equals(basicData.getPrice())){
                    tvCash.setText(basicData.getPrice()+"元");
                    tvReward.setText("[权益会员返"+new BigDecimal(basicData.getPrice()).multiply(new BigDecimal(basicData.getBacksilverratio())).intValue()/100+"银币]");
                }else{
                    tvCash.setText("*元");
                }
                if(null!=basicData.getMarketprice()&&!"".equals(basicData.getMarketprice())){
                    tvOrign.setText("市场价："+basicData.getMarketprice()+"元");
                    tvOrign.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                }else{
                    tvOrign.setText("市场价：");
                }
                if(null!=basicData.getViewnum()&&!"".equals(basicData.getViewnum())){
                    tvView.setText(basicData.getViewnum()+"");
                }else{
                    tvView.setText("");
                }
                if(null!=basicData.getServicetime()&&!"".equals(basicData.getServicetime())){
                    tvTime.setText(basicData.getServicetime()+"分钟");
                }else{
                    tvTime.setText("");
                }
            }
            //初始化详情数据
            detailFragment.initProjectData(result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 上滑悬停
     */
    private void scrollStop() {
        scrollView = (MyScrollView) findViewById(R.id.scrollView);
        linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
        linearScrollBody = (LinearLayout) findViewById(R.id.linearScrollBody);
        linearBegin = (LinearLayout) findViewById(R.id.linearBegin);
        linearStop = (LinearLayout) findViewById(R.id.linearStop);
        scrollView.setOnScrollListener(this);
    }

    private void InitViewPager() {
        tabs = new Button[2];
        tabs[0] = (Button) findViewById(R.id.btDetail);
        tabs[1] = (Button) findViewById(R.id.btComment);
        tabs[0].setSelected(true);
        detailFragment = new BeautifulStoreDetailFragment(id);
        commentFragment = new BeautifulStoreCommentFragment(id);
        fragments= new Fragment[]{detailFragment, commentFragment};
        getSupportFragmentManager().beginTransaction()
                .add(R.id.relaContainer, detailFragment).commit();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        //收藏
        btCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //收藏
                getCollection();
            }
        });
        //分享
        btShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分享
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow();
                }
            }
        });
        btDetail.setOnClickListener(this);
        btComment.setOnClickListener(this);
        tvOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(null==MyApplication.getInstance().getUserId()||"".equals(MyApplication.getInstance().getUserId())){
                        showShortToast("用户未登录，请先登录");
                    }else if (!"".equals(result.getIsSub()))
                        if ("0".equals(result.getIsSub())) {
                            showShortToast("此类项目限次24次/年，已预约满，不可再预约，请选择其他项目！");
                        }else {
                            Intent intent = new Intent(context, SubscribeActivity.class);
                            intent.putExtra("id", id);
                            startActivity(intent);
                        }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                finish();
            }
        });
    }

    private void getCollection() {
        if(!MyTextUtils.isFastDoubleClick()){
            map.clear();
            map.put("ftype", "1");
            map.put("refid", id);
            type = "collection";
            getServer(Url.ADD_FAVORITE, map, "", false, null, "post");
        }
    }

    /**
     * 弹出分享界面
     */
    private void initPopuWindow() {
        popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(btShare, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;
                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }
                new ShareAction(ProjectDetailActivity.this).setPlatform(platform).setCallback(umShareListener).withTitle("美容何必再花钱！消费多少返多少=免费美容！")
                        .withText("手机里装一个自己的美容院，天天“摇钱树+搜红包”消费返银币=实现免费美容，下载即送大礼包！").withTargetUrl(Url.BASE_URL+"/share/inner/servicedetails?sid="+id)
                        .share();
                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功啦");
            }
            type = "shareget";
            getServer(Url.SHARE, null, "", false, null, "get");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showShortToast("分享取消了");
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btDetail:
                btDetail.setSelected(true);
                btComment.setSelected(false);
                btComment.setSelected(false);
                index = 0;
                if(linearScrollBody.getParent() != linearBegin){
                    linearStop.removeView(linearScrollBody);
                    linearBegin.addView(linearScrollBody);
                }
                break;
            case R.id.btComment:
                btDetail.setSelected(false);
                btComment.setSelected(true);
                index = 1;
                if(linearScrollBody.getParent() != linearBegin){
                    linearStop.removeView(linearScrollBody);
                    linearBegin.addView(linearScrollBody);
                }
                break;
        }
        if(index != currentIndex){
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            if(fragments[currentIndex].isAdded()){
                trx.hide(fragments[currentIndex]);
            }
            if(!fragments[index].isAdded()){
                trx.add(R.id.relaContainer, fragments[index]);
            }
            trx.show(fragments[index]).commit();
            tabs[index].setSelected(true);
            tabs[currentIndex].setSelected(false);
            currentIndex = index;
        }
    }

    @Override
    public void onScroll(int scrollY) {
        if(scrollY >= scrollHeight){
            if(linearScrollBody.getParent() != linearStop){
                linearBegin.removeView(linearScrollBody);
                linearStop.addView(linearScrollBody);
            }
        }else{
            if(linearScrollBody.getParent() != linearBegin){
                linearStop.removeView(linearScrollBody);
                linearBegin.addView(linearScrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
